﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using XKJ.OAWeb.Infrastructrue.Helpers.JWT;

namespace XKJ.OAWeb.Api.Config
{
    public static class AuthenConfig
    {
        public static void Authen(this IServiceCollection services, JWTTokenOptions tokenOptions)
        {
            services.AddAuthentication(option =>
            {
                //认证模式
                option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                //咨询模式
                option.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(option =>
            {
                //设置元数据地址或权限是否需要HTTPs
                option.RequireHttpsMetadata = false;
                option.SaveToken = true;
                //Token验证登录
                option.TokenValidationParameters = new TokenValidationParameters
                {
                    //是否验证签名
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(tokenOptions.SigningCredentials)),
                    ValidIssuer = tokenOptions.Issuer,//有效的发行人
                    ValidAudience = tokenOptions.Audience,//受众
                    ValidateIssuer = true,//是否验证发行人
                    ValidateAudience = true,//验证受众
                    ClockSkew = TimeSpan.Zero,
                    ValidateLifetime = true//是否验证过期时间
                };
            });
        }
    }
}
